<?php

/**
 * This file is part of Webman AI.
 *
 * @author    walkor<walkor@workerman.net>
 * @copyright walkor<walkor@workerman.net>
 * @link      http://www.workerman.net/
 */

namespace plugin\ai\app\handler\driver;

use Workerman\Http\Client;
use Workerman\Http\Response;

class Ying extends Base
{

    /**
     * @var string api地址
     */
    protected $api = 'https://dict.youdao.com';

    /**
     * Speech
     * @param $data
     * @param $options
     * @return void
     */
    public function speech($data, $options)
    {
        $headers = $this->getHeaders($options);
        $options = $this->formatOptions($options);
        $requestOptions = [
            'method' => 'GET',
            'data' => ['audio' => $data['input'], 'le' => 'zh'],
            'headers' => $headers,
            'progress' => function ($buffer) use ($options) {
                $options['stream']($buffer);
            },
            'success' => function (Response $response) use ($options) {
                $options['complete'](static::formatResponse((string)$response->getBody()), $response);
            },
            'error' => function ($exception) use ($options) {
                $options['complete']([
                    'error' => [
                        'code' => 'exception',
                        'message' => $exception->getMessage(),
                        'detail' => (string) $exception
                    ],
                ], new Response(0));
            }
        ];
        $http = new Client(['timeout' => 600]);
        $http->request($this->api . '/dictvoice', $requestOptions);
    }

    /**
     * Format audio response.
     * @param $buffer
     * @return array[]|mixed
     */
    public static function formatResponse($buffer)
    {
        $json = json_decode($buffer, true);
        if ($json && !empty($json['error'])) {
            return $json;
        }
        if (strpos(ltrim($buffer),'<html>') === 0) {
            return [
                'error' => [
                    'code' => 'parse_error',
                    'message' => 'Unable to parse response',
                    'detail' => $buffer
                ]
            ];
        }
        return $buffer;
    }

}